package com.hao.ssh;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;

public class LocalCmd {
    /**
     * 直接在本地执行 shell
     *
     * @param commands 执行的脚本
     * @return 执行结果信息
     */
    public static String runLocalShell(String[] commands) {
        Runtime runtime = Runtime.getRuntime();
        Scanner input = null;
        String result = "";
        Process process = null;
        try {
            process = runtime.exec(commands); //等待命令执行完成
            try {
                process.waitFor(10, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            InputStream inputStream = process.getInputStream();
            input = new Scanner(inputStream);
            while (input.hasNextLine()) {
                String line = input.nextLine();
                System.out.println(line);
                result += line + "\n";
            }
            result = commands + "\n" + result; //加上命令本身，打印出来
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (input != null) {
                input.close();
            }
            if (process != null) {
                process.destroy();
            }
        }
        return result;
    }

    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("cmd");
        list.add("/C");
        list.add("dir");

        String result = runLocalShell(list.toArray(new String[list.size()]));
//        System.out.println(result);
    }
}
